package com.openatc.autoprogram.service;

import com.google.gson.Gson;
import com.openatc.autoprogram.model.MessageData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * @Classname MsgService
 * @Description
 * @Date 2022/5/1 22:21
 * @Created by panleilei
 */
@Service
public class MsgService {
    @Value("${openatc.url}")
    private String ip;
    @Value("${openatc.port}")
    private int port;
    /**
     * 向openatc发送消息
     * @param messageData
     */
    public void sendUdpMsgToOpenATC(MessageData messageData) {
        Gson gson = new Gson();
        String s = gson.toJson(messageData);
        byte[] buffer = s.getBytes(StandardCharsets.UTF_8);
        InetSocketAddress address = new InetSocketAddress(ip,port);
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length,address);
        try {
            DatagramSocket dsocket = new DatagramSocket();
            dsocket.send(packet);

        } catch (SocketException e) {
        } catch (IOException e) {
        }

    }


}
